package com.example.bookmaster.app;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;

import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MainActivity extends ActionBarActivity {

    final DatabaseHandle db;
    final Context context = this;

    public MainActivity() {
        db = new DatabaseHandle(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        //            java.util.Date uDate = format.parse("2014-02-01");

//        db.addBook(new Book("0001", "PHP", "Team", "Zend", "2014-01-01"));

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    //search
    public void getBook(View v) throws ParseException {

        if (checkValidBookID(v)) {
            EditText txtId = (EditText) findViewById(R.id.txtBookID);
            EditText txtTitle = (EditText) findViewById(R.id.txtBookTitle);
            EditText txtAuthor = (EditText) findViewById(R.id.txtAuthor);
            EditText txtPublisher = (EditText) findViewById(R.id.txtPublisher);
            EditText txtYear = (EditText) findViewById(R.id.txtYear);
            EditText txtMonth = (EditText) findViewById(R.id.txtMonth);
            EditText txtDay = (EditText) findViewById(R.id.txtDay);

            Book book = db.getBook(txtId.getText().toString().trim());
            //        Log.d("Book", book.getBook_title());
            if (book != null) {
//                Log.i("Bug", book.getPublication_day());
                new AlertDialog.Builder(this)
                        .setTitle("Message")
                        .setMessage("Book is found")
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        })
                        .show();

                txtTitle.setText(book.getBook_title());
                txtAuthor.setText(book.getAuthor_name());
                txtPublisher.setText(book.getPublisher());
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                java.util.Date date = format.parse(book.getPublication_day());
                java.sql.Date newDate = new Date(date.getTime());
                Calendar cal = Calendar.getInstance();
                cal.setTime(newDate);
                int year = cal.get(Calendar.YEAR);
                int month = cal.get(Calendar.MONTH) + 1;
                int day = cal.get(Calendar.DAY_OF_MONTH);
                txtYear.setText(String.valueOf(year));
                txtMonth.setText(String.valueOf(month));
                txtDay.setText(String.valueOf(day));
            } else {
                Log.i("Bug", "run else");
                AlertDialog.Builder alert = new AlertDialog.Builder(this);
                alert.setTitle("Error")
                        .setMessage("Cannot find book ID")
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        })
                        .show();
            }
        }
    }

    public Boolean checkValidBookID(View v) {
        EditText txtBookId = (EditText) findViewById(R.id.txtBookID);

        String Id = txtBookId.getText().toString().trim();
        if (Id.matches("")) {


            new AlertDialog.Builder(this).setTitle("Error")
                    .setMessage("Please input book id")
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {

                        }
                    })
                    .show();
            return false;
        } else {
//            Log.i("Bug", "run alphanumeric");
            Pattern p = Pattern.compile("^[a-zA-Z0-9]*$");
            String check = txtBookId.getText().toString();
            Matcher matcher = p.matcher(check);
            if (!matcher.matches()) {
                new AlertDialog.Builder(this)
                        .setTitle("Error")
                        .setMessage("Please input book ID by alphanumeric characters")
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        })
                        .show();
                return false;
            }
            return true;
        }

    }

    private boolean checkInput(View v) {

        EditText txtTitle = (EditText) findViewById(R.id.txtBookTitle);
        EditText txtAuthor = (EditText) findViewById(R.id.txtAuthor);
        EditText txtPublisher = (EditText) findViewById(R.id.txtPublisher);
        EditText txtYear = (EditText) findViewById(R.id.txtYear);
        EditText txtMonth = (EditText) findViewById(R.id.txtMonth);
        EditText txtDay = (EditText) findViewById(R.id.txtDay);

        String result = "";
        Pattern p = Pattern.compile("^[0-9]*$");
        if (txtTitle.getText().toString().trim().matches(""))
            result += "Please input book title\n";
        else if (txtAuthor.getText().toString().trim().matches(""))
            result += "Please input author name\n";
        else if (txtPublisher.getText().toString().trim().matches(""))
            result += "Please input publishing company\n";
        else if (txtYear.getText().toString().trim().matches(""))
            result += "Please input year\n";
        else if (txtMonth.getText().toString().trim().matches(""))
            result += "Please input month\n";
        else if (txtDay.getText().toString().trim().matches(""))
            result += "Please input day\n";
        else if (!p.matcher(txtYear.getText().toString()).matches() || !p.matcher(txtMonth.getText().toString()).matches() || !p.matcher(txtDay.getText().toString()).matches())
            result += "Please input publication date by numeric characters";
        if (!result.matches("")) {
            new AlertDialog.Builder(context)
                    .setTitle("Error")
                    .setMessage(result)
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {

                        }
                    })
                    .show();
            return false;
        }
        return true;
    }

    //public insert Book
    public void insertBook(final View v) {
        try {
            if (checkValidBookID(v) && checkInput(v)) {

                AlertDialog alert = new AlertDialog.Builder(this)
                        .setTitle("Message")
                        .setMessage("Do you want to register Book?")
                        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                                EditText txtId = (EditText) findViewById(R.id.txtBookID);
                                EditText txtTitle = (EditText) findViewById(R.id.txtBookTitle);
                                EditText txtAuthor = (EditText) findViewById(R.id.txtAuthor);
                                EditText txtPublisher = (EditText) findViewById(R.id.txtPublisher);
                                EditText txtYear = (EditText) findViewById(R.id.txtYear);
                                EditText txtMonth = (EditText) findViewById(R.id.txtMonth);
                                EditText txtDay = (EditText) findViewById(R.id.txtDay);
                                if (checkValidDate(txtYear.getText().toString().trim(), txtMonth.getText().toString().trim(), txtDay.getText().toString().trim())!=null) {
                                    Book book = null;
                                    try {
                                        book = db.getBook(txtId.getText().toString().trim());
                                    } catch (ParseException e) {
                                        e.printStackTrace();
                                    }
                                    if (book == null) {
                                        String bookId = txtId.getText().toString().trim();
                                        String bookTitle = txtTitle.getText().toString().trim();
                                        String authorName = txtAuthor.getText().toString().trim();
                                        String publisher = txtPublisher.getText().toString().trim();
                                        String publicationDay = txtYear.getText().toString().trim() + "-" + txtMonth.getText().toString().trim() + "-" + txtDay.getText().toString().trim();
                                        book = new Book(bookId, bookTitle, authorName, publisher, publicationDay);

                                        if (db.addBook(book)) {

                                            new AlertDialog.Builder(context)
                                                    .setTitle("Message")
                                                    .setMessage("Book is registered")
                                                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                                        @Override
                                                        public void onClick(DialogInterface dialogInterface, int i) {

                                                        }
                                                    })
                                                    .show();
                                        }
                                    } else {
                                        new AlertDialog.Builder(context)
                                                .setTitle("Error")
                                                .setMessage("Book ID is registered. Please choose another ID")
                                                .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialogInterface, int i) {

                                                    }
                                                })
                                                .show();
                                    }
                                }

                            }
                        })
                        .setNegativeButton("No", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.cancel();
                            }
                        })
                        .show();
            }


        } catch (Exception ex) {
            new AlertDialog.Builder(this)
                    .setTitle("Error")
                    .setMessage("DB Error has occurred")
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {

                        }
                    })
                    .show();
        }

    }

    //update book
    public void updateBook(View v) {
        try {
            if (checkInput(v) && checkValidBookID(v)) {

                new AlertDialog.Builder(context)
                        .setTitle("Message")
                        .setMessage("Do you want to update Book?")
                        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                EditText txtId = (EditText) findViewById(R.id.txtBookID);
                                EditText txtTitle = (EditText) findViewById(R.id.txtBookTitle);
                                EditText txtAuthor = (EditText) findViewById(R.id.txtAuthor);
                                EditText txtPublisher = (EditText) findViewById(R.id.txtPublisher);
                                EditText txtYear = (EditText) findViewById(R.id.txtYear);
                                EditText txtMonth = (EditText) findViewById(R.id.txtMonth);
                                EditText txtDay = (EditText) findViewById(R.id.txtDay);

                                String id = txtId.getText().toString().trim();
                                if (checkValidDate(txtYear.getText().toString().trim(), txtMonth.getText().toString().trim(), txtDay.getText().toString().trim()) != null) {
                                    Book book = null;
                                    try {
                                        book = db.getBook(id);
                                    } catch (ParseException e) {
                                        e.printStackTrace();
                                    }
                                    if (book != null) {//check exist book in database
                                        String bookId = txtId.getText().toString().trim();
                                        String bookTitle = txtTitle.getText().toString().trim();
                                        String authorName = txtAuthor.getText().toString().trim();
                                        String publisher = txtPublisher.getText().toString().trim();
                                        String publicationDay = txtYear.getText().toString().trim() + "-" + txtMonth.getText().toString().trim() + "-" + txtDay.getText().toString().trim();

//                                    book.setBook_title(bookTitle);
//                                    book.setPublisher(publisher);
//                                    book.setAuthor_name(authorName);
//                                    book.setPublication_day(publicationDay);
                                        book = new Book(bookId, bookTitle, authorName, publisher, publicationDay);

                                        if (db.updateBook(book)) {//update the book

                                            new AlertDialog.Builder(context)
                                                    .setTitle("Message")
                                                    .setMessage("Book is updated")
                                                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                                        @Override
                                                        public void onClick(DialogInterface dialogInterface, int i) {

                                                        }
                                                    })
                                                    .show();
                                        }
                                    } else {
                                        new AlertDialog.Builder(context)
                                                .setTitle("Error")
                                                .setMessage("Cannot find the Book Id")
                                                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialogInterface, int i) {

                                                    }
                                                })
                                                .show();
                                    }

                                }

                            }
                        })
                        .setNegativeButton("No", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.cancel();
                            }
                        })
                        .show();
            }

        } catch (Exception e) {
            new AlertDialog.Builder(this)
                    .setTitle("Error")
                    .setMessage("DB Error has occurred")
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {

                        }
                    })
                    .show();
        }
    }

    //clear all field
    public void clearData(View v) {
        EditText txtId = (EditText) findViewById(R.id.txtBookID);
        EditText txtTitle = (EditText) findViewById(R.id.txtBookTitle);
        EditText txtAuthor = (EditText) findViewById(R.id.txtAuthor);
        EditText txtPublisher = (EditText) findViewById(R.id.txtPublisher);
        EditText txtYear = (EditText) findViewById(R.id.txtYear);
        EditText txtMonth = (EditText) findViewById(R.id.txtMonth);
        EditText txtDay = (EditText) findViewById(R.id.txtDay);

        txtTitle.setText("");
        txtId.setText("");
        txtAuthor.setText("");
        txtPublisher.setText("");
        txtYear.setText("");
        txtMonth.setText("");
        txtDay.setText("");
    }

    //delete Book
    public void deleteBook(View v) {
        try {
            if (checkValidBookID(v)) {
                new AlertDialog.Builder(context)
                        .setTitle("Message")
                        .setMessage("Do you want to delete book?")
                        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                EditText txtId = (EditText) findViewById(R.id.txtBookID);
//                                 Log.i("id", txtId.getText().toString());
                                String id = txtId.getText().toString().trim();//get book id from text field
                                Book book = null;
                                try {
                                    book = db.getBook(id);//get book by id
                                } catch (ParseException e) {
                                    e.printStackTrace();
                                }
//                                 Log.i("book", book.getBook_id());
                                if (book != null)//check exist of book in database
                                {
                                    if (db.deleteBook(book)) {
                                        new AlertDialog.Builder(context)
                                                .setTitle("Message")
                                                .setMessage("Book is deleted")
                                                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialogInterface, int i) {

                                                    }
                                                })
                                                .show();
                                    }
                                } else {
                                    new AlertDialog.Builder(context)
                                            .setTitle("Error")
                                            .setMessage("Cannot find the Book Id")
                                            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialogInterface, int i) {

                                                }
                                            })
                                            .show();
                                }
                            }
                        })
                        .setNegativeButton("No", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.cancel();
                            }
                        })
                        .show();
            }
        } catch (Exception e) {
            new AlertDialog.Builder(this)
                    .setTitle("Error")
                    .setMessage("DB Error has occurred")
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {

                        }
                    })
                    .show();
        }
    }

    //check valid of date
    private Date checkValidDate(String year, String month, String day) {
        try {

            SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
            java.util.Date date = format.parse(year + "/" + month + "/" + day);
            Date setdate = new Date(date.getTime());
            Log.i("date", setdate.toString());
            return setdate;
        } catch (Exception e) {
            new AlertDialog.Builder(this)
                    .setTitle("Error")
                    .setMessage("Date input wrong, please try again")
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {

                        }
                    })
                    .show();
            return null;
        }
    }
}
